<template>
  <div>
    <el-dialog :title="$t('sidebar.script_generator')" :visible.sync="msg" :modal-append-to-body="false" id="script_generator" width="500px"
      :close-on-press-escape="false" :close-on-click-modal="false" :before-close="handleDialogClose">
      <div>
        <el-form ref="formRef" class="custom-form" :model="formData" label-width="120px" :rules="formRules">
          <el-form-item label="脚本名称" prop="name">
            <el-input type="text" v-model="formData.name" autoComplete="off" />
          </el-form-item>
          <el-form-item label="启动脚本命令" prop="start">
            <el-input type="text" v-model="formData.start" autoComplete="off" />
          </el-form-item>
          <el-form-item label="停止脚本命令" prop="stop">
            <el-input type="text" v-model="formData.stop" autoComplete="off" />
          </el-form-item>
          <el-form-item label="监控进程" prop="monitor">
            <el-input v-model="formData.monitor" :rows="5" type="textarea" placeholder="在监控进程列表中，每一行代表一个进程" />
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { checkScriptName, createScript } from '@/api/tools'
import { vd } from '@/utils/validate'

export default {
  name: 'ScriptForm',
  props: {
    msg: Boolean,
  },
  data() {
    return {
      formData: {
        name: '',
        start: '',
        stop: '',
        monitor: ''
      },
      formRules: {
        name: [vd.required],
        start: [vd.required],
        stop: [vd.required],
        monitor: [vd.required]
      },
      loading: false,
    }
  },
  methods: {
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.loading = true

          // 检测脚本名称是否已存在
          checkScriptName({ filename: this.formData.name }).then((res) => {
            if (res.data.action) {
              // 没有相同名称，创建脚本
              this.handleCreateScript()
            } else {
              // 已有相同的脚本名称
              this.$confirm(`集群内已存在${this.formData.name}脚本，是否要替换？`, '确认生成脚本', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                iconClass: 'el-icon-question',
                beforeClose: (action, instance, done) => {
                  if (action === 'confirm') {
                    // 开启按钮加载
                    instance.confirmButtonLoading = true
                    this.handleCreateScript()
                      .then(() => {
                        instance.confirmButtonLoading = false
                        done()
                        this.handleDialogClose()
                      })
                      .catch(() => {
                        instance.confirmButtonLoading = false
                      })
                  } else {
                    done()
                  }
                }
              }).catch(() => {
                this.loading = false
                this.$message.info('取消替换')
              })
            }
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },

    handleCreateScript() {
      return new Promise((resolve, reject) => {
        createScript(this.formData).then((res) => {
          if (res.data.action) {
            this.loading = false
            const data = res.data.data
            let length = Object.keys(data).length
            const arr = []

            Object.keys(data).forEach((node) => {
              if (data[node].indexOf('failed') > -1 || data[node].indexOf('失败') > -1) {
                arr.push(`<p>节点${node}同步脚本失败，请手动同步脚本到该节点！</p>`)
              } else if (data[node].indexOf('success') > -1 || data[node].indexOf('成功') > -1) {
                arr.push(`<p>节点${node}同步脚本成功！</p>`)
                length = length - 1
              } else {
                arr.push(`<p>节点${node} ${data[node]}</p>`)
              }
            })

            this.$emit('click')

            if (length === 0) {
              this.$message.success('生成脚本成功！')
            } else {
              // 弹窗提示具体节点生成脚本情况
              this.$alert(arr.join(''), '节点生成脚本情况', {
                confirmButtonText: '确认',
                showClose: false,
                type: 'info',
                dangerouslyUseHTMLString: true
              })
            }
            resolve()
          } else {
            this.$message.error(res.data.error)
            this.loading = false
            reject()
          }
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    },

    // 取消
    handleDialogClose() {
      this.$refs.formRef.resetFields()
      this.$store.state.count = "";
    },
  }
}
</script>

<style lang="scss" scoped>
.custom-form {
  width: 90%;
}
.dialog-footer {
  text-align: right;
  margin-top: 20px;

  .el-button+.el-button {
    margin-left: 10px;
  }
}
</style>